#include <math.h>
#include <stdint.h>
#include <stdlib.h>


uint8_t average_rms(uint8_t* array, uint8_t num){
	uint8_t rms = 0;
	uint8_t mean= 0;

	// find mean
	int i;
	for(i = 0; i < num; i++)
		mean += array[i];
	mean /= num;

	// find the rms
	// rms = sqrt(sum of squares of the difference from the mean)
	for(i = 0; i < num; i++){
		uint8_t temp = abs(mean - array[i]);
		rms += temp*temp;
	}
	rms = sqrt(rms);

	// avgerage ignoring any numbers more than 3*sms away from the mean
	uint8_t num_averaged = 0;
	uint16_t avg = 0;
	for(i = 0; i < num; i++){
		if(array[i] < (3*rms)){
			avg += array[i];
			num_averaged++;
		}
	}
	avg = avg / num_averaged;

	return (uint8_t)avg;
}

uint8_t average(uint8_t* array, uint8_t num){
	return average_rms(array, num);
}

